package jl.cts.engine;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import jl.cts.objects.ScoreBar;
import jl.cts.objects.Street;
import jl.cts.util.Properties;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.AttributeSet;
import android.view.View;

public class EngineView extends View implements SensorEventListener {

	private static final int FPS = 24;

	private Paint paint;

	private Street street;

	private int width;
	private int height;

	private ScoreBar scoreBar;

	private float acelX;

	private float acelY;

	private float acelZ;

	public EngineView(Context context) {
		super(context);
		_init(context);
	}

	public EngineView(Context context, AttributeSet attrs) {
		super(context, attrs);
		_init(context);
	}

	private void _init(Context context) {

		width = Properties.SCREENWIDTH;
		height = Properties.SCREENHEIGHT;
		this.setMeasuredDimension(width, height);

		scoreBar = new ScoreBar(context, 0, 0, width, (int) (height * 0.1));

		street = new Street(context, 0, (int) (height * 0.1), width,
				(int) (height * 0.9));

		paint = new Paint();
		paint.setColor(Color.WHITE);

		setTimer();
	}

	public void setTimer() {
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				postInvalidate();
			}
		}, 0, 1000 / FPS);
	}

	@Override
	protected void onDraw(Canvas canvas) {

		if (scoreBar != null) {
			scoreBar.render(canvas, paint);
		}

		if (street != null) {
			street.render(canvas, paint);
		}
	}

	public void onResume() {
		SensorManager sm = (SensorManager) this.getContext().getSystemService(
				Context.SENSOR_SERVICE);
		List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
		if (sensors.size() > 0) {
			sm.registerListener(this, sensors.get(0),
					SensorManager.SENSOR_DELAY_GAME);
		}
	}
	
	public void onStop() {
		SensorManager sm = (SensorManager) this.getContext().getSystemService(
				Context.SENSOR_SERVICE);
		sm.unregisterListener(this);
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	public void onSensorChanged(SensorEvent event) {

		synchronized (this) {
			acelX = event.values[0];
			acelY = event.values[1];
			acelZ = event.values[2];

			street.setAcceleration(acelX, acelY, acelZ);
		}
	}

	

}
